from django.core import serializers
from django.shortcuts import render
from django.http import HttpResponse,JsonResponse,HttpResponseRedirect
from backgroundapp.models import *
from django.core.paginator import Paginator,PageNotAnInteger,EmptyPage
from django.views import View
from django.contrib.auth.models import User,Group,Permission,ContentType
from django.contrib.auth.decorators import login_required,permission_required
from django.contrib.auth import authenticate,login,logout
import json

def get_user_data(request):
    if request.method == 'GET':
        query_name=request.GET.get('id')
        if query_name :
            obj = User.objects.filter(username=query_name).all()
            if obj:
                obj=User.objects.get(username=query_name)
                obj.is_superuser=1
                obj.save()
            else:
                return render(request, 'backgroundapp/error.html', {'msg': "not exists！"})
            types = User.objects.all()
            lis = []
            for type in types:
                dic = {}
                dic['id'] = type.id
                dic['username'] = type.username
                dic['email'] = type.email
                dic['last_login'] = type.last_login
                dic['is_superuser'] = type.is_superuser
                lis.append(dic)
            # 前台传来的页数
            page_index = request.GET.get('page')
            # 前台传来的一页显示多少条数据
            page_limit = request.GET.get('limit')
            # 分页器进行分配
            paginator = Paginator(lis, page_limit)
            # 前端传来页数的数据
            data = paginator.page(page_index)
            # 放在一个列表里
            have_paged_info = [x for x in data]
            # students.count()总数据量，layui的table模块要接受的格式
            dict = {"code": 0, "msg": "", "count": types.count(), "data": have_paged_info}
            return JsonResponse(dict)
        else:
            types = User.objects.all()
            lis = []
            for type in types:
                dic = {}
                dic['id'] = type.id
                dic['username'] = type.username
                dic['email'] = type.email
                dic['last_login'] = type.last_login
                dic['is_superuser'] = type.is_superuser
                lis.append(dic)
            # 前台传来的页数
            page_index = request.GET.get('page')
            # 前台传来的一页显示多少条数据
            page_limit = request.GET.get('limit')
            # 分页器进行分配
            paginator = Paginator(lis, page_limit)
            # 前端传来页数的数据
            data = paginator.page(page_index)
            # 放在一个列表里
            have_paged_info = [x for x in data]
            # students.count()总数据量，layui的table模块要接受的格式
            dict = {"code": 0, "msg": "", "count": types.count(), "data": have_paged_info}
            return JsonResponse(dict)
    else:
        return render(request,'backgroundapp/useradd.html',{'mssg':'非法操作'})

def gotoaddsuperuser(request):
    if request.user.is_authenticated:
        if request.user.is_superuser:
            return render(request, 'backgroundapp/addsuperuser.html', {'username': request.user.username})
        else:
            return render(request, 'backgroundapp/error.html', {'msg': "not superuser!!!!"})
    else:
        return render(request, 'backgroundapp/error.html', {'msg': "You should login first!!!!"})


def test(request):
    return render(request, 'backgroundapp/table_test.html')
def error(request):
    return render(request, 'backgroundapp/error.html')
def get_test_data(request):
    dict={"code":0,"msg":"","count":1000,"data":[{"id":10000,"username":"user-0","sex":"女","city":"城市-0","sign":"签名-0","experience":255,"logins":24,"wealth":82830700,"classify":"作家","score":57},{"id":10001,"username":"user-1","sex":"男","city":"城市-1","sign":"签名-1","experience":884,"logins":58,"wealth":64928690,"classify":"词人","score":27},{"id":10002,"username":"user-2","sex":"女","city":"城市-2","sign":"签名-2","experience":650,"logins":77,"wealth":6298078,"classify":"酱油","score":31},{"id":10003,"username":"user-3","sex":"女","city":"城市-3","sign":"签名-3","experience":362,"logins":157,"wealth":37117017,"classify":"诗人","score":68},{"id":10004,"username":"user-4","sex":"男","city":"城市-4","sign":"签名-4","experience":807,"logins":51,"wealth":76263262,"classify":"作家","score":6},{"id":10005,"username":"user-5","sex":"女","city":"城市-5","sign":"签名-5","experience":173,"logins":68,"wealth":60344147,"classify":"作家","score":87},{"id":10006,"username":"user-6","sex":"女","city":"城市-6","sign":"签名-6","experience":982,"logins":37,"wealth":57768166,"classify":"作家","score":34},{"id":10007,"username":"user-7","sex":"男","city":"城市-7","sign":"签名-7","experience":727,"logins":150,"wealth":82030578,"classify":"作家","score":28},{"id":10008,"username":"user-8","sex":"男","city":"城市-8","sign":"签名-8","experience":951,"logins":133,"wealth":16503371,"classify":"词人","score":14},{"id":10009,"username":"user-9","sex":"女","city":"城市-9","sign":"签名-9","experience":484,"logins":25,"wealth":86801934,"classify":"词人","score":75},{"id":10010,"username":"user-10","sex":"女","city":"城市-10","sign":"签名-10","experience":1016,"logins":182,"wealth":71294671,"classify":"诗人","score":34},{"id":10011,"username":"user-11","sex":"女","city":"城市-11","sign":"签名-11","experience":492,"logins":107,"wealth":8062783,"classify":"诗人","score":6},{"id":10012,"username":"user-12","sex":"女","city":"城市-12","sign":"签名-12","experience":106,"logins":176,"wealth":42622704,"classify":"词人","score":54},{"id":10013,"username":"user-13","sex":"男","city":"城市-13","sign":"签名-13","experience":1047,"logins":94,"wealth":59508583,"classify":"诗人","score":63},{"id":10014,"username":"user-14","sex":"男","city":"城市-14","sign":"签名-14","experience":873,"logins":116,"wealth":72549912,"classify":"词人","score":8},{"id":10015,"username":"user-15","sex":"女","city":"城市-15","sign":"签名-15","experience":1068,"logins":27,"wealth":52737025,"classify":"作家","score":28},{"id":10016,"username":"user-16","sex":"女","city":"城市-16","sign":"签名-16","experience":862,"logins":168,"wealth":37069775,"classify":"酱油","score":86},{"id":10017,"username":"user-17","sex":"女","city":"城市-17","sign":"签名-17","experience":1060,"logins":187,"wealth":66099525,"classify":"作家","score":69},{"id":10018,"username":"user-18","sex":"女","city":"城市-18","sign":"签名-18","experience":866,"logins":88,"wealth":81722326,"classify":"词人","score":74},{"id":10019,"username":"user-19","sex":"女","city":"城市-19","sign":"签名-19","experience":682,"logins":106,"wealth":68647362,"classify":"词人","score":51},{"id":10020,"username":"user-20","sex":"男","city":"城市-20","sign":"签名-20","experience":770,"logins":24,"wealth":92420248,"classify":"诗人","score":87},{"id":10021,"username":"user-21","sex":"男","city":"城市-21","sign":"签名-21","experience":184,"logins":131,"wealth":71566045,"classify":"词人","score":99},{"id":10022,"username":"user-22","sex":"男","city":"城市-22","sign":"签名-22","experience":739,"logins":152,"wealth":60907929,"classify":"作家","score":18},{"id":10023,"username":"user-23","sex":"女","city":"城市-23","sign":"签名-23","experience":127,"logins":82,"wealth":14765943,"classify":"作家","score":30},{"id":10024,"username":"user-24","sex":"女","city":"城市-24","sign":"签名-24","experience":212,"logins":133,"wealth":59011052,"classify":"词人","score":76},{"id":10025,"username":"user-25","sex":"女","city":"城市-25","sign":"签名-25","experience":938,"logins":182,"wealth":91183097,"classify":"作家","score":69},{"id":10026,"username":"user-26","sex":"男","city":"城市-26","sign":"签名-26","experience":978,"logins":7,"wealth":48008413,"classify":"作家","score":65},{"id":10027,"username":"user-27","sex":"女","city":"城市-27","sign":"签名-27","experience":371,"logins":44,"wealth":64419691,"classify":"诗人","score":60},{"id":10028,"username":"user-28","sex":"女","city":"城市-28","sign":"签名-28","experience":977,"logins":21,"wealth":75935022,"classify":"作家","score":37},{"id":10029,"username":"user-29","sex":"男","city":"城市-29","sign":"签名-29","experience":647,"logins":107,"wealth":97450636,"classify":"酱油","score":27}]}
    return HttpResponse(json.dumps(dict), content_type="application/json", )
    # return JsonResponse(dict, safe=False)
def logoutapi(request):
    logout(request)
    return HttpResponseRedirect("/login/")
def MedicineAPI(request):
    if request.user.is_authenticated:
        return render(request, 'backgroundapp/medicineInfo.html', {'username': request.user.username})
    else:
        return render(request,'backgroundapp/error.html',{'msg':"You should login first!!!!"})

def get_medicine_data(request):
    if request.method == 'GET':
        query_name=request.GET.get('id')
        if query_name :
            types = Medicine.objects.filter(id__contains=query_name).all()
            name = Medicine.objects.filter(medicine_name__contains=query_name).all()
            scale = Medicine.objects.filter(scale__contains=query_name).all()
            batch_num =Medicine.objects.filter(batch_num__contains=query_name).all()
            approval_num =Medicine.objects.filter(approval_num__contains=query_name).all()
            effects =Medicine.objects.filter(effects__contains=query_name).all()
            bzq =Medicine.objects.filter(bzq__contains=query_name).all()
            runit_price = Medicine.objects.filter(runit_price__contains=query_name).all()
            wunit_price = Medicine.objects.filter(wunit_price__contains=query_name).all()
            types = types | name | scale | batch_num | approval_num | effects | bzq | runit_price | wunit_price
            lis = []
            for type in types:
                dic = {}
                dic['id'] = type.id
                dic['medicine_name'] = type.medicine_name
                dic['scale'] = type.scale
                dic['batch_num'] = type.batch_num
                dic['approval_num'] = type.approval_num
                dic['effects'] = type.effects
                dic['bzq'] = type.bzq
                dic['runit_price'] = type.runit_price
                dic['wunit_price'] = type.wunit_price
                lis.append(dic)

            # 前台传来的页数
            page_index = request.GET.get('page')
            # 前台传来的一页显示多少条数据
            page_limit = request.GET.get('limit')
            # 分页器进行分配
            paginator = Paginator(lis, page_limit)
            # 前端传来页数的数据
            data = paginator.page(page_index)
            # 放在一个列表里
            have_paged_info = [x for x in data]
            # students.count()总数据量，layui的table模块要接受的格式
            dict = {"code": 0, "msg": "", "count": types.count(), "data": have_paged_info}
            return JsonResponse(dict)

        else:
            types = Medicine.objects.all()
            lis = []
            for type in types:
                dic = {}
                dic['id'] = type.id
                dic['medicine_name'] = type.medicine_name
                dic['scale'] = type.scale
                dic['batch_num'] = type.batch_num
                dic['approval_num'] = type.approval_num
                dic['effects'] = type.effects
                dic['bzq'] = type.bzq
                dic['runit_price'] = type.runit_price
                dic['wunit_price'] = type.wunit_price
                lis.append(dic)
            # 前台传来的页数
            page_index = request.GET.get('page')
            # 前台传来的一页显示多少条数据
            page_limit = request.GET.get('limit')
            # 分页器进行分配
            paginator = Paginator(lis, page_limit)
            # 前端传来页数的数据
            data = paginator.page(page_index)
            # 放在一个列表里
            have_paged_info = [x for x in data]
            # students.count()总数据量，layui的table模块要接受的格式
            dict = {"code": 0, "msg": "", "count": types.count(), "data": have_paged_info}
            return JsonResponse(dict)


    elif request.method == 'POST':

        if request.POST["op"] == "add":

            obj = Medicine.objects.filter(id=request.POST["id"])

            if not obj:

                # 这是增加

                # 增加里面，我前段按照表的字段，凡是不能为空，都是设置的必填

                obj = Medicine(id=request.POST["id"],

                               medicine_name=request.POST["medicine_name"],

                               scale=request.POST["scale"],

                               batch_num=request.POST["batch_num"],

                               approval_num=request.POST["approval_num"],

                               effects=request.POST["effects"],

                               bzq=request.POST["bzq"],

                               runit_price=float(request.POST["runit_price"]),

                               wunit_price=float(request.POST["wunit_price"]))

                obj.save()

                return render(request, 'backgroundapp/medicineInfo.html')

            else:

                return render(request,'backgroundapp/error.html',{'msg':"Can't find the data"})

        if request.POST["op"] == "delete":

            # 这是删除

            # 凡是主键，都是设置的必填，其余都可为空

            print("this is medicine delete!")

            obj = Medicine.objects.filter(id=request.POST["id"])

            if obj:

                obj.delete()

                return render(request, 'backgroundapp/medicineInfo.html')

            else:

                return render(request,'backgroundapp/useradd.html',{'mssg':'id不存在'})

        if request.POST["op"] == "update":

            # 这是修改

            # 凡是主键，都是设置的必填，其余都可为空,为空代表不用修改

            obj = Medicine.objects.filter(id=request.POST["id"])

            if obj:

                obj = Medicine.objects.get(id=request.POST["id"])
                context = {"id": obj.id, "medicine_name": obj.medicine_name, "scale": obj.scale,
                           "batch_num": obj.batch_num, "approval_num": obj.approval_num,
                           "effects": obj.effects, "bzq": obj.bzq, "runit_price": obj.runit_price,
                           "wunit_price": obj.wunit_price}
                obj.id = request.POST["id"]
                if request.POST["medicine_name"]:
                    obj.medicine_name = request.POST["medicine_name"]
                if request.POST["scale"]:
                    obj.scale = request.POST["scale"]
                if request.POST["batch_num"]:
                    obj.batch_num = request.POST["batch_num"]
                if request.POST["approval_num"]:
                    obj.approval_num = request.POST["approval_num"]
                if request.POST["effects"]:
                    obj.effects = request.POST["effects"]
                if request.POST["bzq"]:
                    obj.bzq = request.POST["bzq"]
                if request.POST["runit_price"]:
                    obj.runit_price = float(request.POST["runit_price"])
                if request.POST["wunit_price"]:
                    obj.wunit_price = float(request.POST["wunit_price"])
                obj.save()
                return render(request, 'backgroundapp/medicineInfo.html', context=context)

            else:

                return render(request,'backgroundapp/useradd.html',{'mssg':'不存在这个数据'})

    else:

        return render(request,'backgroundapp/useradd.html',{'mssg':'非法操作'})
def Medicine_Add(request):
    if request.user.is_authenticated:
        if request.user.is_superuser:
            return render(request, 'backgroundapp/medicine_add.html', {'username': request.user.username})
        else:
            return render(request,'backgroundapp/error.html',{'msg':"not superuser!!!!"})
    else:
        return render(request,'backgroundapp/error.html',{'msg':"You should login first!!!!"})
def Medicine_Update(request):
    if request.user.is_authenticated:
        if request.user.is_superuser:
            return render(request, 'backgroundapp/medicine_update.html', {'username': request.user.username})
        else:
            return render(request,'backgroundapp/error.html',{'msg':"not superuser!!!!"})
    else:
        return render(request,'backgroundapp/error.html',{'msg':"You should login first!!!!"})

def Medicine_Delete(request):
    if request.user.is_authenticated:
        if request.user.is_superuser:
            return render(request, 'backgroundapp/medicine_delete.html', {'username': request.user.username})
        else:
            return render(request,'backgroundapp/error.html',{'msg':"not superuser!!!!"})

    else:
        return render(request,'backgroundapp/error.html',{'msg':"You should login first!!!!"})

def WorkerAPI(request):

    if request.user.is_authenticated:
        return render(request, 'backgroundapp/workerInfo.html', {'username': request.user.username})
    else:
        return render(request,'backgroundapp/error.html',{'msg':"You should login first!!!!"})

def get_worker_data(request):
    if request.method=='GET':
        query_name = request.GET.get('id')
        if query_name:
            types = Workerinfo.objects.filter(id__contains=query_name).all()
            worker_name = Workerinfo.objects.filter(worker_name__contains=query_name).all()
            gender = Workerinfo.objects.filter(gender__contains=query_name).all()
            birth = Workerinfo.objects.filter(birth__contains=query_name).all()
            tel = Workerinfo.objects.filter(tel__contains=query_name).all()
            types = types | worker_name | gender | birth | tel
            lis = []
            for type in types:
                dic = {}
                dic['id'] = type.id
                dic['worker_name'] = type.worker_name
                dic['gender'] = type.gender
                dic['birth'] = type.birth
                dic['tel'] = type.tel
                lis.append(dic)

            # 前台传来的页数
            page_index = request.GET.get('page')
            # 前台传来的一页显示多少条数据
            page_limit = request.GET.get('limit')
            # 分页器进行分配
            paginator = Paginator(lis, page_limit)
            # 前端传来页数的数据
            data = paginator.page(page_index)
            # 放在一个列表里
            have_paged_info = [x for x in data]
            # students.count()总数据量，layui的table模块要接受的格式
            dict = {"code": 0, "msg": "", "count": types.count(), "data": have_paged_info}
            return JsonResponse(dict)

        else:
            types = Workerinfo.objects.all()
            lis = []
            for type in types:
                dic = {}
                dic['id'] = type.id
                dic['worker_name'] = type.worker_name
                dic['gender'] = type.gender
                dic['birth'] = type.birth
                dic['tel'] = type.tel
                lis.append(dic)
            # 前台传来的页数
            page_index = request.GET.get('page')
            # 前台传来的一页显示多少条数据
            page_limit = request.GET.get('limit')
            # 分页器进行分配
            paginator = Paginator(lis, page_limit)
            # 前端传来页数的数据
            data = paginator.page(page_index)
            # 放在一个列表里
            have_paged_info = [x for x in data]
            # students.count()总数据量，layui的table模块要接受的格式
            dict = {"code": 0, "msg": "", "count": types.count(), "data": have_paged_info}
            return JsonResponse(dict)
    elif request.method=='POST':
        if request.POST["op"] == "add":
            # 这是增加
            # 增加里面，我前段按照表的字段，凡是不能为空，都是设置的必填
            obj = Workerinfo.objects.filter(id=request.POST["id"])
            if not obj:
                obj = Workerinfo(id=request.POST["id"],
                                 worker_name=request.POST["worker_name"],
                                 gender=request.POST["gender"],
                                 birth=request.POST["birth"],
                                 tel=request.POST["tel"], )
                obj.save()
                return render(request, 'backgroundapp/workerInfo.html')
            else:
                return render(request,'backgroundapp/useradd.html',{'mssg':'id重复了'})
        if request.POST["op"] == "delete":
            # 这是删除
            # 凡是主键，都是设置的必填，其余都可为空
            print("this is  Worker delete!")
            obj = Workerinfo.objects.filter(id=request.POST["id"])
            if obj:
                obj.delete()
                return render(request, 'backgroundapp/workerInfo.html')
            else:
                return render(request,'backgroundapp/useradd.html',{'mssg':'id不存在'})
        if request.POST["op"] == "update":
            # 这是修改
            # 凡是主键，都是设置的必填，其余都可为空,为空代表不用修改
            print("this is worker update!")
            obj = Workerinfo.objects.filter(id=request.POST["id"])
            if obj:
                obj = Workerinfo.objects.get(id=request.POST["id"])
                if request.POST["id"]:
                    obj.id = request.POST["id"]
                if request.POST["worker_name"]:
                    obj.worker_name = request.POST["worker_name"]
                if request.POST["gender"]:
                    obj.gender = request.POST["gender"]
                if request.POST["birth"]:
                    obj.birth = request.POST["birth"]
                if request.POST["tel"]:
                    obj.tel = request.POST["tel"]
                obj.save()
                return render(request, 'backgroundapp/workerInfo.html')
            else:
                return render(request,'backgroundapp/useradd.html',{'mssg':'id不存在'})

    else:
        return render(request,'backgroundapp/useradd.html',{'mssg':'非法操作'})


def Worker_Add(request):
    if request.user.is_authenticated:
        if request.user.is_superuser:
            return render(request, 'backgroundapp/worker_add.html', {'username': request.user.username})
        else:
            return render(request,'backgroundapp/error.html',{'msg':"not superuser!!!!"})

    else:
        return render(request,'backgroundapp/error.html',{'msg':"You should login first!!!!"})
def Worker_Update(request):
    if request.user.is_authenticated:
        if request.user.is_superuser:
            return render(request, 'backgroundapp/worker_update.html', {'username': request.user.username})
        else:
            return render(request,'backgroundapp/error.html',{'msg':"not superuser!!!!"})

    else:
        return render(request,'backgroundapp/error.html',{'msg':"You should login first!!!!"})
def Worker_Delete(request):
    if request.user.is_authenticated:
        if request.user.is_superuser:
            return render(request, 'backgroundapp/worker_delete.html', {'username': request.user.username})
        else:
            return render(request,'backgroundapp/error.html',{'msg':"not superuser!!!!"})

    else:
        return render(request,'backgroundapp/error.html',{'msg':"You should login first!!!!"})


def CustomerAPI(request):
    if request.user.is_authenticated:
        return render(request, 'backgroundapp/customerInfo.html', {'username': request.user.username})
    else:
        return render(request,'backgroundapp/error.html',{'msg':"You should login first!!!!"})

def get_customer_data(request):
    if request.method == 'GET':
        # 只是一个没有感情的返回数据的机器
        print("get  customer!!!!!!!!!")
        query_name = request.GET.get('id')
        if query_name:
            types = Customer.objects.filter(id__contains=query_name).all()
            customer_name = Customer.objects.filter(customer_name__contains=query_name).all()
            tel = Customer.objects.filter(tel__contains=query_name).all()
            address = Customer.objects.filter(address__contains=query_name).all()
            types = types | customer_name | tel|address
            lis = []
            for type in types:
                dic = {}
                dic['id'] = type.id
                dic['customer_name'] = type.customer_name
                dic['tel'] = type.tel
                dic['address'] =type.address
                lis.append(dic)
            # 前台传来的页数
            page_index = request.GET.get('page')
            # 前台传来的一页显示多少条数据
            page_limit = request.GET.get('limit')
            # 分页器进行分配
            paginator = Paginator(lis, page_limit)
            # 前端传来页数的数据
            data = paginator.page(page_index)
            # 放在一个列表里
            have_paged_info = [x for x in data]
            # students.count()总数据量，layui的table模块要接受的格式
            dict = {"code": 0, "msg": "", "count": types.count(), "data": have_paged_info}
            return JsonResponse(dict)
        else:
            types = Customer.objects.all()
            lis = []
            for type in types:
                dic = {}
                dic['id'] = type.id
                dic['customer_name'] = type.customer_name
                dic['tel'] = type.tel
                dic['address'] = type.address
                lis.append(dic)
                # 前台传来的页数
            page_index = request.GET.get('page')
            # 前台传来的一页显示多少条数据
            page_limit = request.GET.get('limit')
            # 分页器进行分配
            paginator = Paginator(lis, page_limit)
            # 前端传来页数的数据
            data = paginator.page(page_index)
            # 放在一个列表里
            have_paged_info = [x for x in data]
            # students.count()总数据量，layui的table模块要接受的格式
            dict = {"code": 0, "msg": "", "count": types.count(), "data": have_paged_info}
            return JsonResponse(dict)
    elif request.method == 'POST':
        if request.POST["op"] == "add":
            # 这是增加
            # 增加里面，我前段按照表的字段，凡是不能为空，都是设置的必填
            obj = Customer.objects.filter(id=request.POST["id"])
            if not obj:
                obj = Customer(id=request.POST["id"],
                               customer_name=request.POST["customer_name"],
                               tel=request.POST["tel"],
                               address=request.POST["address"], )
                obj.save()
                return render(request, 'backgroundapp/customerInfo.html')
            else:
                return render(request,'backgroundapp/error.html',{'msg':"Can't find the data"})
        if request.POST["op"] == "delete":
            # 这是删除
            # 凡是主键，都是设置的必填，其余都可为空
            print("this is  customer delete!")
            obj = Customer.objects.filter(id=request.POST["id"])
            if obj:
                obj.delete()
                return render(request, 'backgroundapp/customerInfo.html')
            else:
                return render(request,'backgroundapp/error.html',{'msg':"Can't find the data"})
        if request.POST["op"] == "update":
            # 这是修改
            # 凡是主键，都是设置的必填，其余都可为空,为空代表不用修改
            print("this is customer update!")
            obj = Customer.objects.filter(id=request.POST["id"])
            if obj:
                obj = Customer.objects.get(id=request.POST["id"])
                obj.id = request.POST["id"]
                if request.POST["customer_name"]:
                    obj.customer_name = request.POST["customer_name"]
                if request.POST["address"]:
                    obj.address = request.POST["address"]
                if request.POST["tel"]:
                    obj.tel = request.POST["tel"]
                obj.save()
                return render(request, 'backgroundapp/customerInfo.html')
            else:
                return render(request,'backgroundapp/error.html',{'msg':"Can't find the data"})
    else:
        return render(request,'backgroundapp/useradd.html',{'mssg':'非法操作'})

def Customer_Add(request):
    if request.user.is_authenticated:
        if request.user.is_superuser:
            return render(request, 'backgroundapp/customer_add.html', {'username': request.user.username})
        else:
            return render(request,'backgroundapp/error.html',{'msg':"not superuser!!!!"})

    else:
        return render(request,'backgroundapp/error.html',{'msg':"You should login first!!!!"})


def Customer_Update(request):
    if request.user.is_authenticated:
        if request.user.is_superuser:
            return render(request, 'backgroundapp/customer_update.html', {'username': request.user.username})
        else:
            return render(request,'backgroundapp/error.html',{'msg':"not superuser!!!!"})

    else:
        return render(request,'backgroundapp/error.html',{'msg':"You should login first!!!!"})


def Customer_Delete(request):
    if request.user.is_authenticated:
        if request.user.is_superuser:
            return render(request, 'backgroundapp/customer_delete.html', {'username': request.user.username})
        else:
            return render(request,'backgroundapp/error.html',{'msg':"not superuser!!!!"})

    else:
        return render(request,'backgroundapp/error.html',{'msg':"You should login first!!!!"})



def ProducerAPI(request):
    if request.user.is_authenticated:
        return render(request, 'backgroundapp/producerInfo.html', {'username': request.user.username})
    else:
        return render(request,'backgroundapp/error.html',{'msg':"You should login first!!!!"})

def get_producer_data(request):
    if request.method == 'GET':
        # 只是一个没有感情的返回数据的机器
        print("get  producer!!!!!!!!!")
        query_name = request.GET.get('id')
        if query_name:
            types = Producer.objects.filter(id__contains=query_name).all()
            producer_name = Producer.objects.filter(producer_name__contains=query_name).all()
            address = Producer.objects.filter(address__contains=query_name).all()
            tel = Producer.objects.filter(tel__contains=query_name).all()
            types = types | producer_name | address | tel
            lis = []
            for type in types:
                dic = {}
                dic['id'] = type.id
                dic['producer_name'] = type.producer_name
                dic['address'] = type.address
                dic['tel'] = type.tel
                lis.append(dic)
            # 前台传来的页数
            page_index = request.GET.get('page')
            # 前台传来的一页显示多少条数据
            page_limit = request.GET.get('limit')
            # 分页器进行分配
            paginator = Paginator(lis, page_limit)
            # 前端传来页数的数据
            data = paginator.page(page_index)
            # 放在一个列表里
            have_paged_info = [x for x in data]
            # students.count()总数据量，layui的table模块要接受的格式
            dict = {"code": 0, "msg": "", "count": types.count(), "data": have_paged_info}
            return JsonResponse(dict)
        else:
            types = Producer.objects.all()

            lis = []
            for type in types:
                print(type)
                dic = {}
                dic['id'] = type.id
                dic['producer_name'] = type.producer_name
                dic['address'] = type.address
                dic['tel'] = type.tel
                lis.append(dic)
            # 前台传来的页数
            page_index = request.GET.get('page')
            # 前台传来的一页显示多少条数据
            page_limit = request.GET.get('limit')
            # 分页器进行分配
            paginator = Paginator(lis, page_limit)
            # 前端传来页数的数据
            data = paginator.page(page_index)
            # 放在一个列表里
            have_paged_info = [x for x in data]
            # students.count()总数据量，layui的table模块要接受的格式
            dict = {"code": 0, "msg": "", "count": types.count(), "data": have_paged_info}
            return JsonResponse(dict)

    elif request.method == 'POST':
        if request.POST["op"] == "add":
            # 这是增加
            # 增加里面，我前段按照表的字段，凡是不能为空，都是设置的必填
            obj = Producer.objects.filter(id=request.POST["id"])
            if not obj:
                obj = Producer(id=request.POST["id"],
                               producer_name=request.POST["producer_name"],
                               tel=request.POST["tel"],
                               address=request.POST["address"], )
                obj.save()
                return render(request, 'backgroundapp/producerInfo.html')
            else:
                return render(request,'backgroundapp/error.html',{'msg':"Can't find the data"})

        if request.POST["op"] == "delete":
            # 这是删除
            # 凡是主键，都是设置的必填，其余都可为空
            print("this is  producer delete!")
            obj = Producer.objects.filter(id=request.POST["id"])
            if obj:
                obj.delete()
                return render(request, 'backgroundapp/producerInfo.html')
            else:
                return render(request,'backgroundapp/error.html',{'msg':"Can't find the data"})
        if request.POST["op"] == "update":
            # 这是修改
            # 凡是主键，都是设置的必填，其余都可为空,为空代表不用修改
            print("this is producer update!")
            obj = Producer.objects.filter(id=request.POST["id"])
            if obj:

                obj = Producer.objects.get(id=request.POST["id"])

                obj.id = request.POST["id"]
                if request.POST["producer_name"]:
                    obj.producer_name = request.POST["producer_name"]
                if request.POST["address"]:
                    obj.address = request.POST["address"]
                if request.POST["tel"]:
                    obj.tel = request.POST["tel"]
                obj.save()
                return render(request, 'backgroundapp/producerInfo.html')
            else:
                return render(request,'backgroundapp/error.html',{'msg':"Can't find the data"})
    else:
        return render(request,'backgroundapp/useradd.html',{'mssg':'非法操作'})

def Producer_Add(request):
    if request.user.is_authenticated:
        if request.user.is_superuser:
            return render(request, 'backgroundapp/producer_add.html', {'username': request.user.username})
        else:
            return render(request,'backgroundapp/error.html',{'msg':"not superuser!!!!"})

    else:
        return render(request,'backgroundapp/error.html',{'msg':"You should login first!!!!"})

def Producer_Update(request):
    if request.user.is_authenticated:
        if request.user.is_superuser:
            return render(request, 'backgroundapp/producer_update.html', {'username': request.user.username})
        else:
            return render(request,'backgroundapp/error.html',{'msg':"not superuser!!!!"})

    else:
        return render(request,'backgroundapp/error.html',{'msg':"You should login first!!!!"})

def Producer_Select(request):
    return render(request, 'backgroundapp/producer_select.html')

def Producerr_Delete(request):
    if request.user.is_authenticated:
        if request.user.is_superuser:
            return render(request, 'backgroundapp/producer_delete.html', {'username': request.user.username})
        else:
            return render(request,'backgroundapp/error.html',{'msg':"not superuser!!!!"})

    else:
        return render(request,'backgroundapp/error.html',{'msg':"You should login first!!!!"})


def StoreAPI(request):
    if request.user.is_authenticated:
        return render(request, 'backgroundapp/storeInfo.html', {'username': request.user.username})
    else:
        return render(request,'backgroundapp/error.html',{'msg':"You should login first!!!!"})

def get_store_data(request):
    if request.method == 'GET':
        #展示  id   medicine_name  quantity   pos
        # query_name = request.GET.get('id')
        # if query_name:
        #     types = Store.objects.filter(medicine__id__contains=query_name).all()
        #     medicine_name = Medicine.objects.filter(id__contains=query_name).all()
        #     quantity = Store.objects.filter(quantity__contains=query_name).all()
        #     pos = Store.objects.filter(pos__contains=query_name).all()
        #     types = types|medicine_name|quantity|pos
        #     lis = []
        #     for type in types:
        #         dic = {}
        #         dic['id'] = type.medicine.id
        #         medicineobj = Medicine.objects.get(id=type.medicine.id)
        #         dic['medicine_name'] = medicineobj.medicine_name
        #         dic['quantity'] = type.quantity
        #         dic['pos'] = type.pos
        #         lis.append(dic)
        #     # 前台传来的页数
        #     page_index = request.GET.get('page')
        #     # 前台传来的一页显示多少条数据
        #     page_limit = request.GET.get('limit')
        #     # 分页器进行分配
        #     paginator = Paginator(lis, page_limit)
        #     # 前端传来页数的数据
        #     data = paginator.page(page_index)
        #     # 放在一个列表里
        #     have_paged_info = [x for x in data]
        #     # students.count()总数据量，layui的table模块要接受的格式
        #     dict = {"code": 0, "msg": "", "count": types.count(), "data": have_paged_info}
        #     return JsonResponse(dict)
        # else:
        types = Store.objects.all()
        lis = []
        for type in types:
            dic = {}
            dic['id'] = type.medicine.id
            medicineobj = Medicine.objects.get(id=type.medicine.id)
            dic['medicine_name'] = medicineobj.medicine_name
            dic['quantity'] = type.quantity
            dic['pos'] = type.pos
            lis.append(dic)
        # 前台传来的页数
        page_index = request.GET.get('page')
        # 前台传来的一页显示多少条数据
        page_limit = request.GET.get('limit')
        # 分页器进行分配
        paginator = Paginator(lis, page_limit)
        # 前端传来页数的数据
        data = paginator.page(page_index)
        # 放在一个列表里
        have_paged_info = [x for x in data]
        # students.count()总数据量，layui的table模块要接受的格式
        dict = {"code": 0, "msg": "", "count": types.count(), "data": have_paged_info}
        return JsonResponse(dict)

def gotologin(request):
    return render(request,'backgroundapp/login.html')
def mylogin(request):
    if request.POST:
        username = request.POST.get('username', None)
        password = request.POST.get('password', None)
        print(username+" login!")
        user = authenticate(username=username, password=password)
        if user is not None:
            if user.is_active:
                login(request, user)
                print(user.is_superuser)
                # return HttpResponseRedirect("/",{'username': username})
                return render(request, 'backgroundapp/home.html', {'username': username})
        else:
            return render(request, 'backgroundapp/login.html', {'mssg': '登录验证失败'})
    else:
        if request.user.is_authenticated:
            return render(request, 'backgroundapp/home.html', {'username': request.user.username})
        else:
            return render(request,'backgroundapp/error.html',{'msg':"You should login first!!!!"})
def gotoadduser(request):
    return render(request,'backgroundapp/useradd.html')

def addUser(request):
    if request.POST:
        username=request.POST.get('username',None)
        password=request.POST.get('pass',None)
        email=request.POST.get('email',None)
        print(password)
        print(email)
        #判断用户名是否重复
        user=User.objects.filter(username=username)
        if len(user)>0:
            return render(request,'backgroundapp/useradd.html',{'mssg':'用户名已经存在'})
        user=User.objects.create_user(username=username,password=password,email=email)
        user.save()
        print('添加成功')
        #添加操作
        return render(request,'backgroundapp/login.html',{'mssg':'用户创建成功'})
    else:
        return render(request,'backgroundapp/useradd.html',{'mssg':'用户创建失败'})

def home(request):
     return render(request,"backgroundapp/home.html")
def add(request):
    return render(request,'backgroundapp/add.html')


def PurchaseAPI(request):
    # types = PurchaseInfoView.objects.all()
    # print(types)
    # return HttpResponse("ok")
    if request.user.is_authenticated:
        return render(request, 'backgroundapp/purchaseInfo.html', {'username': request.user.username})
    else:
        return render(request,'backgroundapp/error.html',{'msg':"You should login first!!!!"})
def get_purchase_data(request):
    if request.method == 'GET':
        # 只是一个没有感情的返回数据的机器
        query_name = request.GET.get('id')
        if query_name:
            print("get_purchase_data!!!!!!!!!")
            types = PurchaseInfoView.objects.filter(id__contains=query_name).all()
            medicine_id = PurchaseInfoView.objects.filter(medicine_id__id__contains=query_name).all()
            medicine_name = PurchaseInfoView.objects.filter(medicine_name__contains=query_name).all()
            producer_id = PurchaseInfoView.objects.filter(producer_id__id__contains=query_name).all()
            producer_name = PurchaseInfoView.objects.filter(producer_name__contains=query_name).all()
            purchase_date = PurchaseInfoView.objects.filter(purchase_date__contains=query_name).all()
            unit_price = PurchaseInfoView.objects.filter(unit_price__contains=query_name).all()
            purchase_quantity = PurchaseInfoView.objects.filter(purchase_quantity__contains=query_name).all()
            total_price = PurchaseInfoView.objects.filter(total_price__contains=query_name).all()
            types = types|medicine_id|producer_id|medicine_name|producer_name|purchase_date|unit_price|purchase_quantity|total_price
            lis = []
            for type in types:
                dic = {}
                dic['id'] = type.id
                dic['medicine_id'] = type.medicine_id.id
                dic['medicine_name'] = type.medicine_name
                dic['producer_id'] = type.producer_id.id
                dic['producer_name'] = type.producer_name
                dic['purchase_date'] = type.purchase_date
                dic['unit_price'] = type.unit_price
                dic['purchase_quantity'] = type.purchase_quantity
                dic['total_price'] = type.total_price
                lis.append(dic)
            # 前台传来的页数
            page_index = request.GET.get('page')
            # 前台传来的一页显示多少条数据
            page_limit = request.GET.get('limit')
            # 分页器进行分配
            paginator = Paginator(lis, page_limit)
            # 前端传来页数的数据
            data = paginator.page(page_index)
            # 放在一个列表里
            have_paged_info = [x for x in data]
            # students.count()总数据量，layui的table模块要接受的格式
            dict = {"code": 0, "msg": "", "count": types.count(), "data": have_paged_info}
            return JsonResponse(dict)
        else:
            types = PurchaseInfoView.objects.all()
            # types = serializers.serialize("json", types)
            lis = []

            for type in types:
                dic = {}
                dic['id'] = type.id
                dic['medicine_id'] = type.medicine_id.id
                dic['medicine_name'] = type.medicine_name
                dic['producer_id'] = type.producer_id.id
                dic['producer_name'] = type.producer_name
                dic['purchase_date'] = type.purchase_date
                dic['unit_price'] = type.unit_price
                dic['purchase_quantity'] = type.purchase_quantity
                dic['total_price'] = type.total_price
                lis.append(dic)
            # 前台传来的页数
            page_index = request.GET.get('page')
            # 前台传来的一页显示多少条数据
            page_limit = request.GET.get('limit')
            # 分页器进行分配
            paginator = Paginator(lis, page_limit)
            # 前端传来页数的数据
            data = paginator.page(page_index)
            # 放在一个列表里
            have_paged_info = [x for x in data]
            # students.count()总数据量，layui的table模块要接受的格式
            dict = {"code": 0, "msg": "", "count": types.count(), "data": have_paged_info}
            return JsonResponse(dict)

    elif request.method == 'POST':
        if request.POST["op"] == "add":
            # 前端传来的字段为：id  medicine_id  producer_id  purchase_quantity  total_price  purchase_date unit_price
            # 这是增加
            # 增加里面，我前段按照表的字段，凡是不能为空，都是设置的必填
            obj = Purchasedetail.objects.filter(id=request.POST["id"],medicine__id=request.POST["medicine_id"],producer__id=request.POST["producer_id"])
            if obj:
                return HttpResponse("进货单重复，请重新输入!")
            obj = Medicine.objects.filter(id=request.POST["medicine_id"])
            if not obj:
                return HttpResponse("药品详细信息请先入库!")
            obj = Producer.objects.filter(id=request.POST["producer_id"])
            if not obj:
                return HttpResponse("生产厂家详细信息请先入库!")
            obj = Purchaseinfo.objects.filter(id=request.POST["id"])
            if not obj:
                obj = Purchaseinfo(id=request.POST["id"],
                                   purchase_date=request.POST["purchase_date"])
                obj.save()
            medicineobj = Medicine.objects.get(id=request.POST["medicine_id"])
            producerobj = Producer.objects.get(id=request.POST["producer_id"])
            obj = Purchasedetail.objects.create(id=request.POST["id"],
                                 purchase_quantity=request.POST["purchase_quantity"],
                                 total_price=request.POST["total_price"],medicine=medicineobj,
                                                producer = producerobj)
            # obj.medicine = medicineobj
            # obj.producer = producerobj
            # obj.save()
            obj = MedicineProducer.objects.filter(medicine__id=request.POST["medicine_id"],
                                                  producer__id=request.POST["producer_id"],)
            if not obj:
                print("changjia yaopin bucunzai")
                obj = MedicineProducer.objects.create(medicine=medicineobj,
                                        producer=producerobj,
                                       unit_price=request.POST["unit_price"])


            # obj = PurchaseInfoView(id=request.POST["id"],
            #                        purchase_date = request.POST["purchase_date"],
            #                        medicine_id = medicineobj,
            #                        medicine_name=medicineobj.medicine_name,
            #                        producer_id=producerobj,
            #                        producer_name=producerobj.producer_name,
            #                        purchase_quantity=request.POST["purchase_quantity"],
            #                        unit_price=request.POST["unit_price"],
            #                        total_price=request.POST["total_price"],)
            return render(request, 'backgroundapp/purchaseInfo.html')
        if request.POST["op"] == "delete":
            # 这是删除
            # 凡是主键，都是设置的必填，其余都可为空
            print("this is  purchase delete!")
            obj = Purchaseinfo.objects.filter(id=request.POST["id"])
            if not obj:
                return HttpResponse("进货单id不存在！")
            obj.delete()
            obj = Purchasedetail.objects.filter(id=request.POST["id"])
            obj.delete()
            return render(request, 'backgroundapp/purchaseInfo.html')
        if request.POST["op"] == "update":
            # id  medicine_id  producer_id  purchase_quantity  total_price  purchase_date unit_price
            # 这是修改
            # 凡是主键，都是设置的必填，其余都可为空,为空代表不用修改
            print("this is purchase update!")
            obj = Purchaseinfo.objects.filter(id=request.POST["id"])
            if not obj:
                return HttpResponse("进货单id不存在！")
            if request.POST["purchase_date"]:
                obj = Purchaseinfo.objects.get(id=request.POST["id"])
                obj.purchase_date = request.POST["purchase_date"]
                obj.save()
            if request.POST["purchase_quantity"]:
                quantity = Purchasedetail.objects.get(id=request.POST["id"], medicine__id=request.POST["medicine_id"],
                                                     producer__id=request.POST["producer_id"]).purchase_quantity
                oldquantity = Store.objects.get(medicine__id=request.POST["medicine_id"]).quantity
                obj= Store.objects.filter(medicine__id=request.POST["medicine_id"]).update(
                                                    quantity=oldquantity+(int)(request.POST["purchase_quantity"])-quantity)
                objs = Purchasedetail.objects.filter(id=request.POST["id"], medicine__id=request.POST["medicine_id"],
                                                     producer__id=request.POST["producer_id"]).update(
                    purchase_quantity=request.POST["purchase_quantity"])
            if request.POST["total_price"]:
                objs = Purchasedetail.objects.filter(id=request.POST["id"], medicine__id=request.POST["medicine_id"],
                                                     producer__id=request.POST["producer_id"]).update(
                    total_price=request.POST["total_price"])
            if request.POST["unit_price"]:
                objs = MedicineProducer.objects.filter(
                                                     medicine__id=request.POST["medicine_id"],
                                                     producer__id=request.POST["producer_id"]).update(
                    unit_price=request.POST["unit_price"])

            # objs = Purchasedetail.objects.filter(id=request.POST["id"],medicine__id=request.POST["medicine_id"],
            #                                      producer__id=request.POST["producer_id"])
            # print("yes")
            # if objs:
            #     obj = Purchasedetail.objects.get(id=request.POST["id"],medicine__id=request.POST["medicine_id"],
            #                                      producer__id=request.POST["producer_id"])
            #     print("yes1")
            #     if request.POST["purchase_quantity"]:
            #         obj.purchase_quantity = request.POST["purchase_quantity"]
            #     if request.POST["total_price"]:
            #         obj.total_price = request.POST["total_price"]
            #     print("yes2")
            #     obj.save()
            # for obj in objs:
            #     if obj.id==request.POST["id"] and obj.medicine.id==request.POST["medicine_id"] and obj.producer.id==request.POST["producer_id"]:
            # obj.id = request.POST["id"]
            # if request.POST["medicine_id"]:
            #     if  not Medicine.objects.filter(id=request.POST["medicine_id"]):
            #         return HttpResponse("该药品详细信息还先入库，请先入库后再修改!")
            #     else:
            #         obj.medicine=request.POST["medicine_id"]
            # if request.POST["producer_id"]:
            #     if  not Producer.objects.filter(id=request.POST["producer_id"]):
            #         return HttpResponse("该生产厂家详细信息还先入库，请先入库后再修改!")
            #     else:
            #         obj.producer = request.POST["producer_id"]
            #         if request.POST["purchase_quantity"]:
            #             obj.purchase_quantity = request.POST["purchase_quantity"]
            #         if request.POST["total_price"]:
            #             obj.total_price = request.POST["total_price"]
            #         obj.save()
            return render(request, 'backgroundapp/purchaseInfo.html')
        else:
            return render(request,'backgroundapp/useradd.html',{'mssg':'非法操作'})


def Purchase_Add(request):
    if request.user.is_authenticated:
        if request.user.is_superuser:
            return render(request, 'backgroundapp/purchase_add.html', {'username': request.user.username})
        else:
            return render(request,'backgroundapp/error.html',{'msg':"not superuser!!!!"})
    else:
        return render(request,'backgroundapp/error.html',{'msg':"You should login first!!!!"})
def Purchase_Delete(request):
    if request.user.is_authenticated:
        if request.user.is_superuser:
            return render(request, 'backgroundapp/purchase_delete.html', {'username': request.user.username})
        else:
            return render(request,'backgroundapp/error.html',{'msg':"not superuser!!!!"})
    else:
        return render(request,'backgroundapp/error.html',{'msg':"You should login first!!!!"})

def Purchase_Update(request):
    if request.user.is_authenticated:
        if request.user.is_superuser:
            return render(request, 'backgroundapp/purchase_update.html', {'username': request.user.username})
        else:
            return render(request,'backgroundapp/error.html',{'msg':"not superuser!!!!"})
    else:
        return render(request,'backgroundapp/error.html',{'msg':"You should login first!!!!"})

def Purchase_Select(request):
    return render(request,'backgroundapp/purchase_select.html', {'username': request.user.username})


def SellAPI(request):
    if request.user.is_authenticated:
        return render(request, 'backgroundapp/sellInfo.html', {'username': request.user.username})
    else:
        return render(request,'backgroundapp/error.html',{'msg':"You should login first!!!!"})

def get_sell_data(request):
    if request.method == 'GET':
        # 只是一个没有感情的返回数据的机器
        query_name = request.GET.get('id')
        if query_name:
            print("get_sell_data!!!!!!!!!")
            types = SellInfoView.objects.filter(id__contains=query_name).all()
            medicine_id  =SellInfoView.objects.filter(medicine_id__id__contains=query_name).all()
            medicine_name =SellInfoView.objects.filter(medicine_name__contains=query_name).all()
            customer_id =SellInfoView.objects.filter(customer_id__id__contains=query_name).all()
            customer_name =SellInfoView.objects.filter(customer_name__contains=query_name).all()
            sell_date =SellInfoView.objects.filter(sell_date__contains=query_name).all()
            way =SellInfoView.objects.filter(way__contains=query_name).all()
            unit_price =SellInfoView.objects.filter(unit_price__contains=query_name).all()
            sell_quantity =SellInfoView.objects.filter(sell_quantity__contains=query_name).all()
            total_price = SellInfoView.objects.filter(total_price__contains=query_name).all()
            types = types|medicine_id|medicine_name|customer_id|customer_name|sell_date|way|unit_price|sell_quantity|total_price
            lis = []
            for type in types:
                dic = {}
                dic['id'] = type.id
                dic['medicine_id'] = type.medicine_id.id
                dic['medicine_name'] = type.medicine_name
                dic['customer_id'] = type.customer_id.id
                dic['customer_name'] = type.customer_name
                dic['sell_date'] = type.sell_date
                dic['way'] = type.way
                dic['unit_price'] = type.unit_price
                dic['sell_quantity'] = type.sell_quantity
                dic['total_price'] = type.total_price
                lis.append(dic)
            # 前台传来的页数
            page_index = request.GET.get('page')
            # 前台传来的一页显示多少条数据
            page_limit = request.GET.get('limit')
            # 分页器进行分配
            paginator = Paginator(lis, page_limit)
            # 前端传来页数的数据
            data = paginator.page(page_index)
            # 放在一个列表里
            have_paged_info = [x for x in data]
            # students.count()总数据量，layui的table模块要接受的格式
            dict = {"code": 0, "msg": "", "count": types.count(), "data": have_paged_info}
            return JsonResponse(dict)
        else:
            types = SellInfoView.objects.all()
            print(types)
            lis = []
            for type in types:
                dic = {}
                dic['id'] = type.id
                dic['medicine_id'] = type.medicine_id.id
                dic['medicine_name'] = type.medicine_name
                dic['customer_id'] = type.customer_id.id
                dic['customer_name'] = type.customer_name
                dic['sell_date'] = type.sell_date
                dic['way'] = type.way
                dic['unit_price'] = type.unit_price
                dic['sell_quantity'] = type.sell_quantity
                dic['total_price'] = type.total_price
                lis.append(dic)
            # 前台传来的页数
            page_index = request.GET.get('page')
            # 前台传来的一页显示多少条数据
            page_limit = request.GET.get('limit')
            # 分页器进行分配
            paginator = Paginator(lis, page_limit)
            # 前端传来页数的数据
            data = paginator.page(page_index)
            # 放在一个列表里
            have_paged_info = [x for x in data]
            # students.count()总数据量，layui的table模块要接受的格式
            dict = {"code": 0, "msg": "", "count": types.count(), "data": have_paged_info}
            return JsonResponse(dict)
    elif request.method == 'POST':
        if request.POST["op"] == "add":
            # 这是增加
            # 增加里面，我前段按照表的字段，凡是不能为空，都是设置的必填
            obj = Selldetail.objects.filter(id=request.POST["id"],
                                            medicine__id=request.POST["medicine_id"])
            if obj:
                return render(request, 'backgroundapp/useradd.html', {'mssg': '售货单id重复，请重新输入!'})
            obj = Medicine.objects.filter(id=request.POST["medicine_id"])
            if not obj:
                return render(request, 'backgroundapp/useradd.html', {'mssg': '药品详细信息请先入库!'})
            obj = Customer.objects.filter(id=request.POST["customer_id"])
            if not obj:
                return render(request, 'backgroundapp/useradd.html', {'mssg': '客户详细信息请先入库!'})
            obj = Sellinfo.objects.filter(id=request.POST["id"])

            medicineobj = Medicine.objects.get(id=request.POST["medicine_id"])
            customerobj = Customer.objects.get(id=request.POST["customer_id"])
            if not obj:

                obj = Sellinfo(id=request.POST["id"],
                                   sell_date=request.POST["sell_date"],customer=customerobj,
                               way = request.POST["way"])
                obj.save()
            if request.POST["way"]:
                if request.POST["way"] == "零售":
                    obj = Selldetail.objects.create(id=request.POST["id"],
                                                        sell_quantity=request.POST["sell_quantity"],
                                                        total_price=medicineobj.runit_price*(int)(request.POST["sell_quantity"]),
                                                    medicine=medicineobj,
                                                   )
                if request.POST["way"] == "批发":
                    obj = Selldetail.objects.create(id=request.POST["id"],
                                                    sell_quantity=request.POST["sell_quantity"],
                                                    total_price=medicineobj.wunit_price * (int)(
                                                        request.POST["sell_quantity"]),
                                                    medicine=medicineobj,
                                                    )
            if not request.POST["way"]:
                way = Sellinfo.objects.get(id=request.POST["id"]).way
                if way == "零售":
                    obj = Selldetail.objects.create(id=request.POST["id"],
                                                    sell_quantity=request.POST["sell_quantity"],
                                                    total_price=medicineobj.runit_price * (int)(
                                                        request.POST["sell_quantity"]),
                                                    medicine=medicineobj,
                                                    )
                else:
                    obj = Selldetail.objects.create(id=request.POST["id"],
                                                    sell_quantity=request.POST["sell_quantity"],
                                                    total_price=medicineobj.wunit_price * (int)(
                                                        request.POST["sell_quantity"]),
                                                    medicine=medicineobj,
                                                    )
            return render(request, 'backgroundapp/sellInfo.html')


        if request.POST["op"] == "delete":
            # 这是删除
            # 凡是主键，都是设置的必填，其余都可为空
            print("this is  sell delete!")
            obj = Selldetail.objects.filter(id=request.POST["id"])
            if not obj:
                return render(request,'backgroundapp/error.html',{'msg':"Can't find the data"})
            obj.delete()
            obj = Sellinfo.objects.filter(id=request.POST["id"])
            obj.delete()
            return render(request, 'backgroundapp/sellInfo.html')

        if request.POST["op"] == "update":
            # 这是修改
            # 凡是主键，都是设置的必填，其余都可为空,为空代表不用修改
            print("this is sell update!")

            obj = Sellinfo.objects.filter(id=request.POST["id"])
            if not obj:
                return render(request, 'backgroundapp/error.html', {'msg': "进货单id不存在！"})
            if request.POST["sell_date"]:
                obj = Sellinfo.objects.get(id=request.POST["id"])
                obj.sell_date = request.POST["sell_date"]
                obj.save()
            if request.POST["sell_quantity"]:
                quantity = Selldetail.objects.get(id=request.POST["id"], medicine__id=request.POST["medicine_id"],
                                            ).sell_quantity
                oldquantity = Store.objects.get(medicine__id=request.POST["medicine_id"]).quantity
                obj = Store.objects.filter(medicine__id=request.POST["medicine_id"]).update(
                    quantity=oldquantity - (int)(request.POST["sell_quantity"]) + quantity)
                if request.POST["way"]:
                    if request.POST["way"] == "零售":
                        r = Medicine.objects.get(id=request.POST["medicine_id"]).runit_price
                        Selldetail.objects.filter(id=request.POST["id"],
                                                  medicine__id=request.POST["medicine_id"],
                                                  ).update(
                            total_price=(int)(request.POST["sell_quantity"])*r)
                    else:
                        r = Medicine.objects.get(id=request.POST["medicine_id"]).wunit_price
                        Selldetail.objects.filter(id=request.POST["id"],
                                                  medicine__id=request.POST["medicine_id"],
                                                  ).update(
                            total_price=(int)(request.POST["sell_quantity"]) * r)
                else:
                    way = Sellinfo.objects.get(id=request.POST["id"]).way
                    if way == "零售":
                        r = Medicine.objects.get(id=request.POST["medicine_id"]).runit_price
                        Selldetail.objects.filter(id=request.POST["id"],
                                                  medicine__id=request.POST["medicine_id"],
                                                  ).update(
                            total_price=(int)(request.POST["sell_quantity"])*r)
                    else:
                        r = Medicine.objects.get(id=request.POST["medicine_id"]).wunit_price
                        Selldetail.objects.filter(id=request.POST["id"],
                                                  medicine__id=request.POST["medicine_id"],
                                                  ).update(
                            total_price=(int)(request.POST["sell_quantity"]) * r)
                objs = Selldetail.objects.filter(id=request.POST["id"],
                                                     medicine__id=request.POST["medicine_id"],
                                                     ).update(sell_quantity=request.POST["sell_quantity"])

            if request.POST["total_price"]:
                objs = Selldetail.objects.filter(id=request.POST["id"],
                                                     medicine__id=request.POST["medicine_id"],
                                                     ).update(total_price=request.POST["total_price"])

            if request.POST["way"]:
                objs = Sellinfo.objects.filter(id=request.POST["id"],).update(way=request.POST["way"])

            return render(request, 'backgroundapp/sellInfo.html')
    else:
        return render(request,'backgroundapp/useradd.html',{'mssg':'非法操作'})

def Sell_Add(request):
    if request.user.is_authenticated:
        if request.user.is_superuser:
            return render(request, 'backgroundapp/sell_add.html', {'username': request.user.username})
        else:
            return render(request,'backgroundapp/error.html',{'msg':"not superuser!!!!"})
    else:
        return render(request,'backgroundapp/error.html',{'msg':"You should login first!!!!"})

def Sell_Delete(request):
    if request.user.is_authenticated:
        if request.user.is_superuser:
            return render(request, 'backgroundapp/sell_delete.html', {'username': request.user.username})
        else:
            return render(request,'backgroundapp/error.html',{'msg':"not superuser!!!!"})
    else:
        return render(request,'backgroundapp/error.html',{'msg':"You should login first!!!!"})

def Sell_Update(request):
    if request.user.is_authenticated:
        if request.user.is_superuser:
            return render(request, 'backgroundapp/sell_update.html', {'username': request.user.username})
        else:
            return render(request,'backgroundapp/error.html',{'msg':"not superuser!!!!"})
    else:
        return render(request,'backgroundapp/error.html',{'msg':"You should login first!!!!"})

def Sell_Select(request):
    return render(request,'backgroundapp/sell_select.html', {'username': request.user.username})


def Medicine_producerAPI(request):
    if request.user.is_authenticated:
        return render(request, 'backgroundapp/medicine_producerInfo.html', {'username': request.user.username})
    else:
        return render(request,'backgroundapp/error.html',{'msg':"You should login first!!!!"})

def get_medicine_producer_data(request):
    if request.method == 'GET':
        # 只是一个没有感情的返回数据的机器
        query_name = request.GET.get('id')
        if query_name:
            types = Medicine_producerInfoView.objects.filter(medicine_id__id__contains=query_name).all()
            medicine_name = Medicine_producerInfoView.objects.filter(medicine_name__contains=query_name).all()
            producer_id = Medicine_producerInfoView.objects.filter(producer_id__id__contains=query_name).all()
            producer_name = Medicine_producerInfoView.objects.filter(producer_name__contains=query_name).all()
            unit_price = Medicine_producerInfoView.objects.filter(unit_price__contains=query_name).all()
            types = types | medicine_name | producer_id | producer_name | unit_price
            lis = []
            for type in types:
                dic = {}
                dic['medicine_id'] = type.medicine_id.id
                dic['medicine_name'] = type.medicine_name
                dic['producer_id'] = type.producer_id.id
                dic['producer_name'] = type.producer_name
                dic['unit_price'] = type.unit_price
                lis.append(dic)
            # 前台传来的页数
            page_index = request.GET.get('page')
            # 前台传来的一页显示多少条数据
            page_limit = request.GET.get('limit')
            # 分页器进行分配
            paginator = Paginator(lis, page_limit)
            # 前端传来页数的数据
            data = paginator.page(page_index)
            # 放在一个列表里
            have_paged_info = [x for x in data]
            # students.count()总数据量，layui的table模块要接受的格式
            dict = {"code": 0, "msg": "", "count": types.count(), "data": have_paged_info}
            return JsonResponse(dict)
        else:
            types = Medicine_producerInfoView.objects.all()
            lis = []
            for type in types:
                dic = {}
                dic['medicine_id'] = type.medicine_id.id
                dic['medicine_name'] = type.medicine_name
                dic['producer_id'] = type.producer_id.id
                dic['producer_name'] = type.producer_name
                dic['unit_price'] = type.unit_price
                lis.append(dic)
                # 前台传来的页数
            page_index = request.GET.get('page')
            # 前台传来的一页显示多少条数据
            page_limit = request.GET.get('limit')
            # 分页器进行分配
            paginator = Paginator(lis, page_limit)
            # 前端传来页数的数据
            data = paginator.page(page_index)
            # 放在一个列表里
            have_paged_info = [x for x in data]
            # students.count()总数据量，layui的table模块要接受的格式
            dict = {"code": 0, "msg": "", "count": types.count(), "data": have_paged_info}
            return JsonResponse(dict)
    elif request.method == 'POST':
        if request.POST["op"] == "add":
            #前端字段分别为：medicine_id   producer_id   unit_price
            # 这是增加
            # 增加里面，我前段按照表的字段，凡是不能为空，都是设置的必填
            obj = Medicine.objects.filter(id=request.POST["medicine_id"])
            if not obj:
                return render(request, 'backgroundapp/error.html', {'msg': "药品详细信息先入库！"})
            obj = Producer.objects.filter(id=request.POST["producer_id"])
            if not obj:
                return render(request, 'backgroundapp/error.html', {'msg': "厂家详细信息先入库！"})
            medicineobj = Medicine.objects.get(id=request.POST["medicine_id"])
            producerobj = Producer.objects.get(id=request.POST["producer_id"])
            obj = MedicineProducer.objects.create(medicine=medicineobj,
                           producer=producerobj,
                           unit_price=request.POST["unit_price"], )

            return render(request, 'backgroundapp/medicine_producerInfo.html')
        if request.POST["op"] == "delete":
            # 这是删除
            # 凡是主键，都是设置的必填，其余都可为空
            print("this is  medicine_producer delete!")
            obj = MedicineProducer.objects.filter(medicine=request.POST["medicine_id"],
                                                  producer=request.POST['producer_id'])
            if obj:
                obj.delete()
                return render(request, 'backgroundapp/medicine_producerInfo.html')
            else:
                return render(request, 'backgroundapp/error.html', {'msg': "not exists！"})
        if request.POST["op"] == "update":
            # 这是修改
            # 凡是主键，都是设置的必填，其余都可为空,为空代表不用修改
            print("this is MedicineProducer update!")
            obj = MedicineProducer.objects.filter(medicine=request.POST["medicine_id"],
                                                  producer=request.POST['producer_id'])
            if obj:
                obj = MedicineProducer.objects.get(medicine=request.POST["medicine_id"],
                                                   producer=request.POST['producer_id'])
                # if request.POST["medicine_id"]:
                #     obj.medicine = request.POST["medicine_id"]
                # if request.POST["producer_id"]:
                #     obj.producer = request.POST["producer_id"]
                if request.POST["unit_price"]:
                    obj = MedicineProducer.objects.filter(medicine=request.POST["medicine_id"],
                                                          producer=request.POST['producer_id']).update(
                        unit_price=request.POST["unit_price"]
                    )
                return render(request, 'backgroundapp/medicine_producerInfo.html')
            else:
                return render(request, 'backgroundapp/error.html', {'msg': "not exists！"})
    else:
        return render(request, 'backgroundapp/error.html', {'msg': "非法操作"})

def Medicine_producer_Add(request):
    if request.user.is_authenticated:
        if request.user.is_superuser:
            return render(request, 'backgroundapp/medicine_producerInfo_add.html', {'username': request.user.username})
        else:
            return render(request,'backgroundapp/error.html',{'msg':"not superuser!!!!"})
    else:
        return render(request,'backgroundapp/error.html',{'msg':"You should login first!!!!"})

def Medicine_producer_Delete(request):
    if request.user.is_authenticated:
        if request.user.is_superuser:
            return render(request,'backgroundapp/medicine_producerInfo_delete.html', {'username': request.user.username})
        else:
            return render(request,'backgroundapp/error.html',{'msg':"not superuser!!!!"})
    else:
        return render(request,'backgroundapp/error.html',{'msg':"You should login first!!!!"})

def Medicine_producer_Update(request):
    if request.user.is_authenticated:
        if request.user.is_superuser:
            return render(request,'backgroundapp/medicine_producerInfo_update.html', {'username': request.user.username})
        else:
            return render(request,'backgroundapp/error.html',{'msg':"not superuser!!!!"})
    else:
        return render(request,'backgroundapp/error.html',{'msg':"You should login first!!!!"})

def Medicine_producer_Select(request):
    return render(request,'backgroundapp/medicine_producer_select.html', {'username': request.user.username})


def index(request):
    return render(request, 'backgroundapp/index.html')

def get_mas(request):
    if request.method == "POST":
        title = request.POST['title']
        username = request.POST['username']
        phone = request.POST['phone']
        email = request.POST['email']
        return render(request, 'backgroundapp/table.html', {'title': title, 'username': username, 'phone': phone, 'email': email})
    else:
        return render(request,'backgroundapp/useradd.html',{'mssg':'非法操作'})
